<template>
  <div class="bill-uploader">
    <el-upload
      class="upload-demo"
      drag
      :show-file-list="false"
      :action="apiUrl"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :headers="uploadHeaders"
      :data="uploadData"
      :before-upload="beforeUploadCheck"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
    </el-upload>
    <div class="upload-tips">
      <h3>上传说明：</h3>
      <p>1. 上传清晰的票据图片</p>
      <p>2. 系统将自动识别票据信息</p>
      <p>3. 上传成功后数据将自动填充到表格中</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
// import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
import { UploadFilled } from "@element-plus/icons-vue"

// 定义事件
const emit = defineEmits(["upload-success", "upload-error"])

// 上传API地址
const apiUrl = import.meta.env.VITE_BASE_API + "/Ocr/recognizeGeneral"
const uploadHeaders = {
  "X-Token": getToken()
}
const uploadData = {
  type: "enter"
}

// 上传文件列表
// const fileList = ref<any[]>([])

// 上传成功处理
const handleUploadSuccess = (response: any) => {
  const data = response.data
  const code = response.code

  console.log("上传成功", response)
  if (code === 200 && data && data.data && data.data.length > 0) {
    ElMessage.success("票据识别成功")
    // 向父组件发送成功事件，并传递识别结果
    emit("upload-success", data.data)
  } else {
    ElMessage.error("票据识别失败，请重新上传")
    emit("upload-error", "识别失败")
  }
}

// 上传失败处理
const handleUploadError = (error: any) => {
  ElMessage.error("图片上传失败")
  emit("upload-error", error)
}

// 上传前校验图片
const beforeUploadCheck = (file: File) => {
  const isImage = file.type.startsWith("image/")
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error("上传文件必须是图片格式!")
    return false
  }
  if (!isLt5M) {
    ElMessage.error("上传图片大小不能超过 5MB!")
    return false
  }

  return true
}
</script>

<style scoped lang="scss">
.bill-uploader {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.upload-demo {
  width: 100%;
  max-width: 500px;
  margin-bottom: 20px;
}

.upload-tips {
  width: 100%;
  max-width: 500px;
  margin-top: 20px;
  padding: 15px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
}

.upload-tips h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #409eff;
  font-size: 16px;
}

.upload-tips p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

:deep(.el-upload.is-drag) {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
